﻿using System;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
using ExceptionReporting;
using SmartHealthCare.Properties;
using SmartHealthCare.Utils;

namespace SmartHealthCare.Frm
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            _lvlAppName.Text = Application.ProductName;
        }

        private void BntCancelarClick(object sender, EventArgs e)
        {
            Close();
        }

        private void BntAceptarClick(object sender, EventArgs e)
        {
            var userManager = new ProviderService(Settings.Default.CredentiaslUrl);
            try
            {
                //
                bool authenticated = userManager.Authenticate(Settings.Default.AppName, _txtUser.Text, _txtPassword.Text);
                DialogResult = authenticated ? DialogResult.OK : DialogResult.Cancel;
                if (authenticated)
                {
                    //
                    var rManager = (IUserManager)userManager;
                    //
                    var roles = rManager.GetRoles(Settings.Default.AppName, _txtUser.Text);
                    //
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(
                                                                       _txtUser.Text, "Custom_System"), roles);
                    //
                    userManager.Dispose();
                    //
                    Close();
                }
            }
            catch (Exception ex)
            {
                var reporter = new ExceptionReporter();
                reporter.ReadConfig();
                reporter.Show(ex);
                //
                userManager.Dispose();
            }
        }

    }
}
